﻿using Abp.Application.Services;
using Abp.AutoMapper;
using RMM.Cates.Dtos;
using RMM.Core.Cates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RMM.Cates
{
    public class CateAppService : ICateAppService
    {
        private readonly ICateService _cateService;

        public CateAppService(ICateService cateService)
        {
            _cateService = cateService;
        }

        public async Task<ResultDto> GetCateListAsync()
        {
            var parent = (await _cateService.GetAll())
                .Where(p => p.HasChildren == true && p.Depth == 1)
                .OrderByDescending(p => p.DisplaySequence)
                .MapTo<List<CateDto>>();
            var child = (await _cateService.GetAll())
                .Where(p => p.HasChildren == false && p.Depth == 2);

            parent.ForEach(p => 
            {
                p.childs = child.Where(x => x.ParentId == p.Id).OrderByDescending(x => x.Depth).MapTo<List<CateChildDto>>();
            });

            return ResultDto.Success(parent);
        }

        public async Task<ResultDto> GetCateByChinese(string chinese)
        {
            chinese = chinese.Trim();
            var result = (await _cateService.GetAll())
                .Where(p=>!p.HasChildren && p.ParentId != 0)
                .Where(p => p.PinYin.Contains(chinese)|| p.Name.Contains(chinese))
                .ToList();
            return ResultDto.Success(result.MapTo<List<CateDto>>());
        }
    }
}
